package com.bjy.qa.util.security;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.ParserConfig;
import com.bjy.qa.entity.Response;
import com.bjy.qa.enumtype.ErrorCode;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用户访问无权限资源 时的异常（用户登录后，请求一个受保护的资源，又没权限时触发）
 */
@Component
public class AccessDeniedPointImpl implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json");
        httpServletResponse.getWriter().println(JSONObject.toJSONString(Response.fail(ErrorCode.UNAUTHORIZED, null))); // 403
        httpServletResponse.getWriter().flush();
    }
}
